const state = {
  count: 999,
  cartList: JSON.parse(localStorage.cartList || '[]'),
  isChecked: true
}

// mutations用于保存更新
const mutations = {
  'ADD_CART' (state, payload) {
    let flag = false
    state.cartList.forEach(item => {
      if (item.id === payload.id) {
        item.issale += payload.issale
        flag = true
      }
    })
    if (!flag) {
      state.cartList.push(payload)
    }
    localStorage.cartList = JSON.stringify(state.cartList)
  },
  // 更新每个选中的
  'UPDATE_CHECKED'(state, payload) {
    state.cartList.forEach(item => {
      if (item.id === payload.id) {
        item.checked = payload.checked
      }
    })
    localStorage.cartList = JSON.stringify(state.cartList)
  },
  // change_count修改数量
  CHANGE_COUNT(state, payload) {
    state.cartList.forEach(item => {
      if (item.checked === payload.checked) {
        item.issale += payload
        return true
      }
    })
    localStorage.cartList = JSON.stringify(state.cartList)
  },
  // change_checked更新每个
  CHANGE_CHECKED(state, payload) {
    state.cartList.forEach(item => {
      if (item.id === payload.id) {
        item.checked = payload.checked
      }
    })
    localStorage.cartList = JSON.stringify(state.cartList)
  },
  // get_allcheck全选
  GET_ALLCHECK(state, payload) {
    state.cartList.forEach(item => {
      item.checked = !payload
    })
  },
  // 删除商品
  'DELETE'(state, payload) {
    state.cartList.forEach((item, index) => {
      if (index === payload) {
        state.cartList.splice(index, 1)
      }
    })
    localStorage.cartList = JSON.stringify(state.cartList)
  }
}

const actions = {

}

const getters = {
  getAllChecked(state) {
    return state.cartList.every(item => item.checked)
  },
  // 计算购物车总数量
  getAllCount(state) {
    let c = 0
    state.cartList.forEach(item => {
      c += item.issale
    })
    return c
  },
  // 计算购物车总价格
  getAllPrice(state) {
    let p = 0
    state.cartList.forEach(item => {
      if (item.checked) {
        p += item.issale * item.price * 100
      }
    })
    return p
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}